package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper mapper;

    //登录
    @Override
    public R login(Employee employee) {
        if (employee==null){
            return R.error("参数非法");
        }
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee employees = mapper.selectOne(wrapper);
        if (employees == null){
            return R.error("该员工不存在");
        }
        if (!employees.getPassword().equals(password)){
            return R.error("密码错误");
        }
        if (employees.getStatus() != 1){
            return R.error("员工已被禁用");
        }
        return R.success(employees);
    }

    //分页条件查询
    @Override
    public R findPage(Integer page, Integer pageSize, String name) {

        Page<Employee> p = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        if (null!=name){
            wrapper.like(Employee::getName,name);
        }
        Page<Employee> employeePage = mapper.selectPage(p, wrapper);
        return R.success(employeePage);
    }

    //修改数据和状态
    @Override
    public R updateStatus(Employee employee) {
        //先判断是否为非法参数
        if (employee == null){
            return R.error("参数非法");
        }
        //再根据id查询出来所有数据
        Employee employee1 = mapper.selectById(employee.getId());
        if (employee1 == null){
            return R.error("此员工不存在");
        }
        mapper.updateById(employee);
        return R.success("修改成功");
    }
}
